data "kubernetes_pod" "pod" {
  metadata {
    name = "ansible-cicd-pod"
    namespace = "default"
  }
}

locals {
    pods     = length(var.pods) > 0 ? var.pods: var.pod_list
}

resource "kubernetes_deployment" "deploy" {
  metadata {
    name = lookup(local.pods[2],"pod_name")
    namespace = lookup(local.pods[2],"ns")
    labels = {
      "app" = "nginx"
    }
  }
  spec {
    selector {
      match_labels = {
        "app" = "nginx"
      }
    }
    template {
      metadata {
        labels = {
          "app" = "nginx"
        }
      }
      spec {
        container {
          name = lookup(element(local.pods[2].container[*],0),"container_name")
          image = lookup(element(local.pods[2].container[*],0),"image")
          port {
            container_port = lookup(element(local.pods[2].container[*],0),"container_port")
            protocol      = "TCP"
          }
        }
        container {
          name = lookup(element(local.pods[2].container[*],1),"container_name")
          image = lookup(element(local.pods[2].container[*],1),"image")
          port {
            container_port = lookup(element(local.pods[2].container[*],1),"container_port")
            protocol      = "TCP"
          }
        }
      }
    }
  }
}


resource "kubernetes_manifest" "pod" {
  manifest = {
    "apiVersion" = "v1"
    "kind"       = "Pod"
    "metadata" = {
      "name"      = "label-demo"
      "namespace" = "default"
      "labels" = {
        "app"         = "nginx"
        "environment" = "production"
      }
    }
    "spec" = {
      "containers" = [
        {
          "image" = "nginx:1.7.9"
          "name"  = "nginx"
          "ports" = [
            {
              "containerPort" = 80
              "protocol"      = "TCP"
            },
          ]
          env = [
            {
              "name" = "VAR1"
              "valueFrom" = {
                "fieldRef" = {
                  "fieldPath" = "metadata.namespace"
                }
              }
            },
            {
              "name"  = "VAR2"
              "value" = "http://127.0.0.1:8200"
            },
          ]
        },
      ]
    }
  }
}